<html>
<div id="loading">
<img src=images/loading.gif> <font color=#008080 size=3><b> Please wait a second ...</b></font>
</div>
<script>
function hideLoading()
{
  var disp = document.getElementById('loading');
  disp.innerHTML = '';
}

function clearKeyIds(id)
{
	var v = document.getElementById(id).value;
	//alert(v.indexOf('...'));
	if (v.indexOf('...') > 0) {
		document.getkeys.ids.value = '';
	}
}

function updEg()
{
  var ops = document.getkeys.idtype;
  //alert (ops.selectedIndex);
  //alert (ops[0].value);
  var disp = document.getElementById('ids');
  switch (ops.selectedIndex) {
  	case 0: disp.innerHTML = "bnhtrkvrbfnbblthfjhtdribvduguikurnufgrfttrrv\n" + "...\n"; break;
  	case 1: disp.innerHTML = "1081\n" + "...\n"; break;
  	case 2: disp.innerHTML = "j9903837\n" + "...\n"; break;
  } 
}

function submitGetKeys() 
{
	var f = document.getkeys;

	if (f.idtype.value == 'sn') {
		alert('Not yet implemented, coming soon...');
		return;
	}
	
	f.ids.value == trimString(f.ids.value);
	if (f.ids.value.length < 1 || f.ids.value.indexOf("..") != -1) {
		alert('Enter information of your Yubikeys');
		return;
	}
	
	f.submit();	
}
</script>

<body>

<?php require_once '../yubiphpbase/appinclude.php';
require_once '../yubiphpbase/yubi_lib.php';
include 'head.htm';

if (($usrid = getUsrIdFromSession()) <= 0) {
	echo TIMEDOUT;
	exit;
}

$_SESSION['tab'] = 0;
$act = getHttpVal('act', 'findkey');
$otp = strtolower(getHttpVal('otp', '')); // otp or client id
$start = getHttpVal('start', 0);
//echo 'act='.$act.', id='.getHttpVal('id',-1).', counter='.getHttpVal('counter',-1);

if (strcmp($act,'upd_key')==0 && ($id=getHttpVal('id',-1)) > 0) {
  if (($counter = getHttpVal('counter', -1)) < 0 || $counter > 65536) {
	$_SESSION['alert'] = 'Invalid counter value';
  } else {
	$notes = getHttpVal('notes', '');
	$active = getHttpVal('active', 1);
	$client = getHttpVal('client', -1);
	$stmt = 'UPDATE yubikeys SET notes='.mysql_quote($notes).
		', counter='.mysql_quote($counter).', active='.mysql_quote($active);
	if (isRootAdm() && $client >= 0) {
		$stmt .= ', client_id='.mysql_quote($client);
	}
	$stmt .= ' WHERE id='.$id;
	if ($r = query($stmt)) {
		$_SESSION['alert'] = 'Yubikey-'.$id.' was updated successfully';
	} else {
		$_SESSION['alert'] = 'Yubikey update failed! '.$contactAdm;
	}
  }
  $act = 'findkey';
  $attrName=getHttpVal('attr_name', 'id');
  $attrVal=getHttpVal('attr_val', $id);
} else {  
  $attrName=getHttpVal('attr_name', '');
  if ($attrName == 'otp') {
  	$attrVal = $otp;
  } else {
  	$attrVal=getHttpVal('attr_val', $otp); // otp or client id
  }
}

if (showMyKeys($act, $start, $attrName, $attrVal) == 0) {
    echo '<h4>No Yubikeys!</h4>';
}

// If client id = 0, meaning it's the root user, display all clients
function displayKey($row, $toggle) {
	$tokId = $row['tokenId'];
	$devId = b64ToModhex($tokId);
	$keyId = $row['id'];
	$client = $row['client_id'];

    echo '<tr '.($toggle ? 'bgcolor=#eeeeee' : '').'><td align=center valign=top><font size=1>'.
	  '<form method=POST action=all_keys.php>'.
	  '<input name=act type=hidden value=upd_key>'.
	  '<input name=otp type=hidden value='.$devId.'>'.
	  '<input name=id type=hidden value='.$row['id'].'>';
	
	if ($keyId == $_SESSION['keyid']) {
		echo '<img src=images/yubiright_16x16.gif title="This is the admin Yubikey you are using to log in!"><p>';
	} else if (isAdmKey($keyId)) {
		echo '<img src=images/admkey.gif title="This is an admin Yubikey"><p>';
	}
  
	echo  $row['id'].'</td>';

	if (isRootAdm()) {
	  echo '<td nowrap align=center><font size=1>'.
		makePopupURL('edit_client.php?client='.$client,$client,500,'#BB0000','Client Info').		
		'. issue to:<p><input name=client size=2 value='.$client.'>'.
		'</td>';
	}

	echo '<td>';
	echo '<select name=active>';
	if ($keyId != $_SESSION['keyid']) {
		echo '<option value="0" '.($row['active']==0 ? 'selected' : '').'>Inactive'.
			 '<option value="1" '.($row['active']==1 ? 'selected' : '').'>Active';
	} else {
		echo '<option value=1>Active';
	}
	echo '</select>';
	echo '</td>';

	echo '<td><font size=1>' . $row['created'] . '</td>';
	echo '<td><font size=1>' . $row['accessed'] . '</td>';
	echo '<td><font size=1>' . $tokId .
		'<br>('. $devId .')<br>('. b64ToHex($tokId).')</td>';
	echo '<td><input name=counter value="'.$row['counter'].'" size=2 maxlength=9></td>';
	if (isRootAdm()) {
		echo '<td><font size=1>' . $row['low'] . '</td>'.
			 '<td><font size=1>' . $row['high'] . '</td>';
	}
	echo '<td><textarea name=notes cols=10 rows=2 class=inputtxt>'.$row['notes'].'</textarea></td>';
	echo '<td><input type=submit value="Update" class=buttonLinkSmall></form></td></tr>';
		
} // End displayKey

// $act: operation code = findkey | list_keys
// $otp: modhex OTP from a Yubikey
function showMyKeys($act, $start, $attrName, $attrVal) {
  $client = $_SESSION['client'];
//  echo 'act='.$act.', attrName='.$attrName.', val='.$attrVal;
  $stmt = 'SELECT id,client_id,active,created,accessed,tokenId,counter,low,high,notes'.
		' FROM yubikeys ';
  if ($act == 'findkey') {
	if (isRootAdm() && $attrName=='client_id' && is_numeric($attrVal)) { // adm can see keys of any client
  		$stmt .= 'WHERE client_id='.mysql_quote($attrVal);
  	} else if ($attrName=='otp') {
  		$devId = substr($attrVal, 0, 12);
  		$stmt .= 'WHERE tokenId='.mysql_quote(modhexToB64($devId));
	} else if ($attrName=='id') {
  		$stmt .= 'WHERE id='.mysql_quote($attrVal);
  	} else {
  		$act = 'list_keys';
  	}
  } else {
  	$act = 'list_keys';
  }

  if (!isRootAdm()) { // If not root, can only see your own Yubikeys
   	if (strpos($stmt, 'WHERE') === false) { 
  		$stmt .= ' WHERE '; 
  	} else {
  		$stmt .= ' AND ';
  	}
  	$stmt .= ' client_id='.$client;
  }
  
  $stmt .= ' LIMIT ' . $start . ', ' . MAX_PER_PAGE;
  
  writeLog($stmt, true);
  
  echo '<table border=0 width=100%><tr><td valign=top colspan=9 align=left><font size=2>';
  
  if (isRootAdm()) {
    if ($attrName == 'client_id') {
    	echo makePopupURL('edit_client.php?client='.$attrVal,'Client-'.$attrVal,500,'#BB0000','Client Info').
		  ' has '.numOfYubikeys($attrVal,1).' active Yubikeys, '.
    	  numOfYubikeys($attrVal,0).' inactive Yubikeys.';
    } else {
		echo 'There are '.numOfYubikeys(-1,1).' active Yubikeys, '.numOfYubikeys(-1,0).
			' inactive Yubikeys.';
    }
  } else {
    $a = getClientInfo($client);
  	echo 'You have '.$a['num_active'].' active Yubikeys, '.$a['num_inactive'].' inactive Yubikeys. Your account was created since '.$a['created'];
  }
  funcBar($act, $attrName, $attrVal);
  echo '</td></tr><tr><td height=8></td></tr>';
   
  ////// Find matching yubikeys
  //   
  //if (strlen($attrVal) < 1) { return 1; }
  $r = query($stmt);
  $n=mysql_num_rows($r);  	
  
  $title = '<tr bgcolor=#ADFF2F><th><font size=1>Key<br>ID</th>';
  if (isRootAdm()) {
	$title .= '<th><font size=1>Client</th>';
  }
  $title .= '<th><font size=1>State</th><th><font size=1>Created (UTC)</th><th><font size=1>Accessed (UTC)</th>'.
	'<th><font size=1>YubikeyID<br>base64<br>(modhex)<br>(hex)</th><th><font size=1>Counter</th>';
  if (isRootAdm()) {
  	$title .= '<th><font size=1>Low</th><th><font size=1>High</th>';
  }
  $title .= '<th><font size=1>Note</th><th></th></tr>';
  
  echo $title;
  
  $i=0;
  while ($row=mysql_fetch_assoc($r)) {  
	displayKey($row, $i % 2);
//	print_r($row);
	if (++$i % 21 == 0) {
		echo $title;
	}
  }
  
  mysql_free_result($r);
  echo '</table>';
  
  echo '<br><font color=#008080 size=2><b>Showing ' . $i . ' record(s)</b></font><br><br>';
  
  if ($i < MAX_PER_PAGE) {
  	return ($i > 0 ? $i : -1);
  }
  
  echo '<h3><a href=#top>^ TOP</a><center><a name=BOT></a>';
  
  if ($attrName =='client_id') {
  	$filter = '&act=findkey&attr_name=client_id&attr_val='.$attrVal;
  } else {
  	$filter ='';
  }
  
  if ($start > 0) {
  	if (($s = $start - MAX_PER_PAGE) < 0) { $s = 0; }  	
  	echo '<a href=all_keys.php?act=list_keys&start='.$s.$filter.'>PREV</a> | ';
  }

  if ($i >= MAX_PER_PAGE-1) {  	
  	echo '<a href=all_keys.php?act=list_keys&start='.($start+MAX_PER_PAGE).$filter.'>NEXT</a>';
  }
  
  echo '</h3></center>';
    
  return $n;

} // End showMyAccts

// op = list_keys, findkey
function funcBar($act, $attrName) {
	global $page;
	
	echo '<table border=0 width=80%>'.
	  '<tr><td colspan=9 height=10></td></tr>';

    echo '<tr>';

	if ('list_keys' != $act) {
    	echo '<tr><td valign=top> ';
    	divBut(150, $page.'?act=list_keys','<font size=2>>> List All Yubikeys</font>');
    	echo '</td><td width=10></td><td width=30 nowrap valign=top>&nbsp;or&nbsp;</td>';
	}

    echo '<td nowrap align=right valign=top><font size=2>' .
      '<form autocomplete=off method=POST action=all_keys.php>' .
      '<font color=#008080 size=2><b>'.
      'Find your Yubikey by its </b></font>'.      
      '<select name=attr_name>'.
      '<option value=otp>OTP';
      if (isRootAdm()) {
      	echo '<option value=client_id';
	  	if ($attrName=='client_id') {
			echo ' selected';
	  	}
	    echo '>Client ID';
      }
      echo '</select></td>'.
	   '<td valign=top align=left><font size=1>'.
		'<input name=act value=findkey type=hidden>'.
		'<input name=otp size=60 maxlength=100 class=inputtxt value="">'.
	   '<td valign=top>»</td>'.
		'<td align=left valign=top><input type=submit value=Find class=buttonLinkO></form></td>'.
       '</td>';

  	echo '</tr>';

    echo '<tr><td colspan=9 align=left><hr size=1>'.     
      '<form name=getkeys id=getkeys autocomplete=off method=POST action=get_keys.php>'.
	  '<table border=0 width=90%>'.
	  '<tr><td colspan=9 align=center><font color=#008080 size=2><b>'.
	   'Retrieve AES secret keys by Yubikey IDs:</b><br><br>'.
	  '</td></tr>'.
	  '<tr><td valign=top>' .
	  '<font size=2 color=#AA0000><p>'.
	  	'» Choose a Yubikey ID type:<br>'.
		'<select id=idtype name=idtype onchange="updEg()">'.
	    '<option value=tokid>Yubikey Token ID or OTP'.
		'<option value=keyid>ID <font size=1>(1st column in List All Yubikeys)</font>'.
	    '<option value=sn>Yubikey Serial Number'.
	    '</select></td>'.
	    '<td align=left>»</td>'.
		'<td><font size=2 color=#AA0000>Enter them here, one Yubikey id per row:</font><br>'.
		'<textarea name=ids id=ids rows=2 cols=47 onclick="clearKeyIds(\'ids\')">'.
		"ujjdfbtdkidthrirhctgkcgbjjlbrfdtenntkhginciu\n".
		"...\n".
		'</textarea><p>'.
	  '</td><td>»</td><td>' .
	  '<input class=buttonLinkO type=button value="Retrieve" onclick="submitGetKeys();">'.	  
	  '</td></tr></table>'.
	  '</form>'.
	  
      '</td></tr>';  	
  	
	echo '</table><hr size=1>';
}

?>

<script>
hideLoading();
</script>
</body>
</html>
